'''
Created on Oct 14, 2012

@author: jason
'''
import pandas as pd
from matplotlib.pyplot import plot, figure, savefig, xlabel, ylabel
from scipy.interpolate import KroghInterpolator
from scipy.interpolate.fitpack2 import UnivariateSpline
from statsmodels.api import OLS
import numpy

infile = 'data.csv'
outfile = 'plot'
extension = 'png'
yname = 'Intensity'
xname = 'Time'


def linear_part(x, y):
    val = []
    x = numpy.array(x)
    X = numpy.array([numpy.ones(len(x)),x]).transpose()
    print X
    figure()
    plot(x,y)
    x_plot = []
    for i in range(4,len(x)):
        if i % 10 != 0:
            continue
        model = OLS(y[0:i],X[0:i,:])
        fit = model.fit()
        y_ = fit.predict(X)
        plot(x,y_)
        val.append(numpy.mean(y-y_))
        x_plot.append(x[i])
    savefig('testplot1.png')
    figure()
    plot(x_plot,val,'r+')
    savefig('testplot.png')
    1/0
    return fit




#Read data into pandas
data = pd.read_csv(infile, delimiter='\t')
print data.columns
shape = data.shape


#Subtract off the first row
#data = data - data.ix[0]

#Fit the models


x = data.ix[:,0]
figure()
for col in range(1,shape[1]):
    if col < 10:
        continue
    y = data.ix[:,col]
    interp = linear_part(x,y)
    plot(x,y,'.')
    plot(x,interp(x),'_')
    ylabel(yname)
    xlabel(xname)
savefig(outfile + '.' + extension)



